<template>
  <view class="user-edit-page">
    <!-- 头像修改区域 -->
    <view class="avatar-section">
      <text class="section-title">头像</text>
      <button
        class="avatar-btn"
        open-type="chooseAvatar"
        @chooseavatar="handleChooseAvatar"
      >
        <image class="avatar-img" :src="avatarUrl" mode="aspectFill" />
      </button>
      <text class="tip-text">点击修改头像（支持JPG/PNG）</text>
    </view>

    <!-- 昵称修改区域 -->
    <view class="nickname-section">
      <text class="section-title">昵称</text>
      <nut-input
        v-model="nickname"
        type="nickname"
        placeholder="请输入昵称"
        border
        @change="handleNicknameChange"
        :max-length="20"
        class="nickname-input"
      />
      <text class="tip-text">支持特殊符号和emoji表情</text>
    </view>

    <view class="nickname-section">
      <text class="section-title">手机</text>
      <view class="phone-input">
        <nut-input
          v-model="phone"
          placeholder="请输入手机号"
          border
          :max-length="20"
          class="num-input"
        />
        <nut-button
          type="primary"
          plain
          shape="square"
          class="bind-btn"
          open-type="getPhoneNumber"
          @getphonenumber="getPhoneNumber"
          >绑定手机</nut-button
        >
      </view>

      <text class="tip-text">请输入手机号</text>
    </view>

    <!-- 提交按钮 -->
    <nut-button
      type="primary"
      block
      class="submit-btn"
      @click="handleSubmit"
      :disabled="!isFormChanged"
    >
      保存修改
    </nut-button>

    <!-- 头像预览弹窗 -->
    <nut-popup position="center" v-model:visible="showAvatarPreview" round>
      <image :src="tempAvatar" mode="aspectFit" class="avatar-preview" />
      <nut-button type="primary" @click="uploadAvatar" class="confirm-btn">
        确认使用
      </nut-button>
    </nut-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import Taro from "@tarojs/taro";
import { showToast, showLoading, hideLoading } from "@tarojs/taro";
import { store } from "@/store/index";
import http from "@/utils/http";
import { globalState } from "@/store/globalStore";

// 用户状态管理
const { info } = store.storeState;
const defaultAvatar = "https://static.xxxx.com/default-avatar.png"; // 默认头像

// 响应式数据
const avatarUrl = ref(info.value.avatar_url || defaultAvatar);
const nickname = ref(info.value.name || "");
const phone = ref(info.value.phone || "");
const tempAvatar = ref(""); // 临时头像路径
const showAvatarPreview = ref(false);
const originalAvatar = ref(avatarUrl.value);
const originalNickname = ref(nickname.value);

// import { store } from "@/store/index";
// const { info, user, userType } = store.storeState;

console.log("info", info.value)

Taro.setNavigationBarTitle({
  title: "用户信息",
});

// 计算表单是否修改
const isFormChanged = computed(() => {
  return !!nickname.value
});

// 选择头像回调（微信官方规范）
const handleChooseAvatar = async (e: any) => {
  // const { avatarUrl: tempPath } = e.detail
  // tempAvatar.value = tempPath
  console.log("e.detail", e.detail);

  // showAvatarPreview.value = true
  const res = await http.upload(e.detail.avatarUrl);
  console.log("res &&&", res);
  avatarUrl.value = res;
};

// 上传头像到服务器
const uploadAvatar = async () => {
  showLoading({ title: "上传中..." });

  try {
    const res = await Taro.uploadFile({
      url: "https://api.yourserver.com/upload/avatar",
      filePath: tempAvatar.value,
      name: "avatar",
      // header: { 'Authorization': `Bearer ${userStore.token}` }
    });

    const data = JSON.parse(res.data);
    if (data.code === 200) {
      avatarUrl.value = data.data.url;
      showToast({ title: "头像上传成功", icon: "success" });
    } else {
      throw new Error(data.message || "上传失败");
    }
  } catch (err) {
    showToast({ title: err.message || "网络错误", icon: "error" });
  } finally {
    hideLoading();
    showAvatarPreview.value = false;
  }
};

// 昵称变更处理（兼容真机BUG）
const handleNicknameChange = (e) => {
  nickname.value = e.detail.value.trim().slice(0, 20);
};

// 提交修改
const handleSubmit = async () => {
  if (!validateForm()) return;

  showLoading({ title: "保存中..." });
  http
    .postQuery("/api/user/update", {
      name: nickname.value,
      avatarUrl: avatarUrl.value,
      phone: phone.value
    })
    .then((res) => {
      console.log("res", res);
      if (res.code == 0) {
        showToast({ title: "保存成功", icon: "success" });
        Taro.navigateBack();
      }
    });
};

// 表单验证
const validateForm = (): boolean => {
  if (!nickname.value) {
    showToast({ title: "昵称不能为空", icon: "none" });
    return false;
  }

  if (nickname.value.length < 2) {
    showToast({ title: "昵称至少2个字符", icon: "none" });
    return false;
  }

  return true;
};

const handleLogin = async () => {
  return new Promise(async (resolve) => {
    const loginRes = await Taro.login();
    console.log("loginRes", loginRes);
    // return;

    if (loginRes.code) {
      // console.log("code:", res);
      http.postQuery("/api/weixin/getToken", {
            code: loginRes.code,
            nickName: info.value.name,
            avatarUrl: info.value.avatar_url,
            referralCode: '',
          })
        .then((res) => {
          console.log("res", res);
          // return;
          if (res.code === 0) {
            // isBusiness.value = res.data.userType == "B";
            globalState.setToken(res.data.token);
            // globalState.getUserInfo();
            store.setToken(res.data.token);
            store.setUserType(res.data.userType);
            store.getUserInfo();
            resolve(true);
          } else {
            resolve(false);
          }
        });
    }
  });
};

async function getPhoneNumber(e) {
  console.log("e", e);
  if (e.detail.errMsg === "getPhoneNumber:ok") {
    const { encryptedData, iv } = e.detail;
    // 这里需要将 encryptedData 和 iv 发送到服务器端进行解密
    console.log("加密数据：", encryptedData);
    console.log("加密算法的初始向量：", iv);
    const suc = await handleLogin()
    if(!suc){
      return;
    }
    http
      .postQuery("/api/user/getPhone", {
        encryptedData,
        iv,
      })
      .then((res) => {
        console.log("res", res);
        if(res.code == 0){
          const obj = JSON.parse(res.data)
          phone.value = obj.phoneNumber
        }
      });
  } else {
    console.log("用户拒绝授权获取手机号");
    Taro.showToast({
      title: "用户拒绝授权获取手机号",
      icon: "none",
    });
  }
}
</script>

<style lang="scss">
/* 750rpx设计稿基准 */
$design-width: 750rpx;

.user-edit-page {
  padding: 40rpx;
  background-color: #f8f9fb;
  min-height: 100vh;
  box-sizing: border-box;
}

.section-title {
  display: block;
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 30rpx;
}

.avatar-section {
  background: #fff;
  border-radius: 24rpx;
  padding: 40rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.03);

  .avatar-btn {
    padding: 0;
    background: transparent;
    border: none;
    line-height: 1;

    &::after {
      border: none;
    }
  }
}

.nickname-section {
  background: #fff;
  border-radius: 24rpx;
  padding: 40rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.03);
  margin-bottom: 40rpx;

  .nut-input {
    margin: 20rpx 0 !important;
    padding: 0 !important;
  }

  .nickname-input {
    border-radius: 16rpx;
    overflow: hidden;
    width: 100%;
    display: flex;
    border: 2rpx solid #eee;
    padding: 0 20rpx;
    height: 100rpx;
    font-size: 32rpx;
  }
}

.tip-text {
  display: block;
  font-size: 26rpx;
  color: #999;
  margin-top: 20rpx;
}

.submit-btn {
  margin-top: 80rpx;
  height: 96rpx;
  border-radius: 48rpx;
  font-size: 34rpx;
  // background: linear-gradient(90deg, #ff5e3a, #ff2a6a);
  border: none;

  &:disabled {
    opacity: 0.6;
  }
}

.avatar-preview {
  width: 80vw;
  height: 80vw;
  max-width: 600rpx;
  max-height: 600rpx;
}

.confirm-btn {
  margin-top: 40rpx;
  width: 100%;
  border-radius: 48rpx;
  height: 88rpx;
}

.avatar-img {
  width: 160rpx;
  height: 160rpx;
  border-radius: 50%;
  background: #999;
}

.phone-input {
  display: flex;
  align-items: center;
  gap: 20rpx;
  .num-input {
    flex: 1;
    border-radius: 16rpx;
    overflow: hidden;
    width: 100%;
    display: flex;
    border: 2rpx solid #eee;
    padding: 0 20rpx;
    height: 100rpx;
    font-size: 32rpx;
  }
  .bind-btn {
    width: 200rpx;
    height: 100rpx;
  }
}
</style>
